﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WebApiV001.Domain;
using WebApiV001.Domain.Entity;
using WebApiV001.Interface;

namespace WebApiV001.Implement.Data
{
    public class EfRespository<T> : IRepository<T> where T:BaseEntity
    {
        private readonly Admin3200DbContext _db;

        public EfRespository(Admin3200DbContext db)
        {
            _db = db;
        }

        private DbSet<T> entity;

        private DbSet<T> Entity
        {
            get
            {
                if (entity == null)
                {
                    entity = _db.Set<T>();
                }
                return entity;
            }
        }
       
        public IQueryable<T> Table
        {
            get
            {
                return Entity;
            }
        }

        public void Add(T entity)
        {
            _db.Add(entity);
            _db.SaveChanges();
        }

        public void Add(IEnumerable<T> entites)
        {
            _db.AddRange(entites);
            _db.SaveChanges();
        }

        public void Delete(T entity)
        {
            _db.Remove(entity);
            _db.SaveChanges();
        }

        public void Delete(IEnumerable<T> entites)
        {
            _db.RemoveRange(entites);
            _db.SaveChanges();
        }


        public T GetById(int id)
        {
            return Entity.Where(x => x.Id == id).FirstOrDefault();
        }

        public void Update(T entity)
        {
            _db.Update(entity);
            _db.SaveChanges();
        }

        public void Update(IEnumerable<T> entites)
        {
            _db.UpdateRange(entites);
            _db.SaveChanges();
        }

    }
}
